<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter title="更新卡券信息" :width="drawerWith" @ok="handleSubmit">
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/form';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { memberCardFormSchema } from '../data/data';
import { updateMemberCard } from '../data/api';
const drawerWith = ref('40%');
// 声明Emits
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, saveOrUpdate, validate }] = useForm({
  labelWidth: 150,
  labelCol: { span: 4 },
  schemas: memberCardFormSchema,
});

const [registerDrawer, { setDrawerProps, changeLoading, closeDrawer }] = useDrawerInner(async data => {
  await resetFields();
  changeLoading(false);
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    await setFieldsValue({
      ...data.record,
    });
  }
});

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await updateMemberCard(values);
    }
    closeDrawer();
    emit('success', true);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
